-- ============================================
-- CLASSEMENT - SNOUB CASINO
-- Affiche le top des joueurs par solde de points.
-- Nécessite : Advanced Computer + Advanced Monitor + Wired Modem
-- ============================================

local REFRESH_SECONDS = 5
local TOP_N = 10

local bank = dofile("client_solde.lua")

local mon = peripheral.find("monitor")
if not mon then
    error("Aucun monitor trouve ! Colle un Advanced Monitor a cote du computer.")
end

mon.setTextScale(0.5)
local prevTerm = term.redirect(mon)
local w, h = term.getSize()

local function centerText(y, text, textColor, bgColor)
    term.setBackgroundColor(bgColor or colors.black)
    term.setTextColor(textColor or colors.white)
    local x = math.floor((w - #text) / 2) + 1
    term.setCursorPos(x, y)
    term.write(text)
end

local RANK_COLOR = { colors.yellow, colors.lightGray, colors.orange }

local function rankColor(i)
    return RANK_COLOR[i] or colors.white
end

local function draw()
    term.setBackgroundColor(colors.black)
    term.clear()
    centerText(1, "=== SNOUB CASINO ===", colors.yellow)
    centerText(2, "CLASSEMENT", colors.white)

    local list, err = bank.getLeaderboard(TOP_N)

    if err and #list == 0 then
        centerText(5, "Serveur banque injoignable...", colors.red)
        return
    end

    if #list == 0 then
        centerText(5, "Aucun joueur enregistre pour le moment.", colors.lightGray)
        return
    end

    local startY = 4
    local colW = math.min(w - 4, 40)
    local x1 = math.floor((w - colW) / 2) + 1

    for i, entry in ipairs(list) do
        local y = startY + (i - 1) * 2
        local rankLabel = "#" .. i
        local line = rankLabel .. "  " .. entry.player
        local pointsLabel = entry.balance .. " pts"

        term.setBackgroundColor(colors.black)
        term.setTextColor(rankColor(i))
        term.setCursorPos(x1, y)
        term.write(line)

        term.setCursorPos(x1 + colW - #pointsLabel, y)
        term.write(pointsLabel)
    end

    centerText(h, "Actualise toutes les " .. REFRESH_SECONDS .. "s", colors.lightGray)
end

-- === PROGRAMME PRINCIPAL ===
draw()

while true do
    sleep(REFRESH_SECONDS)
    draw()
end